package android.scanner.scan.module;


import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.scanner.scan.R;
import android.scanner.scan.module.model.ScanModel;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.ButterKnife;

import butterknife.InjectView;
import butterknife.OnClick;
import com.zilla.android.lib.ui.zxing.mipca.MipcaActivityCapture;
import com.zilla.android.zillacore.libzilla.db.DBOperator;

import java.io.IOException;
import java.util.List;

public class MainActivity extends ActionBarActivity implements View.OnClickListener{

    private final static int SCANNIN_GREQUEST_CODE = 1;
    Button mBtnScan;
    Button mBtnSynchronous;
    TextView mResult;
    ImageView mQrcodeBitmap;
    private boolean playBeep = true;
    private MediaPlayer mediaPlayer;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate = true;
    private static final long VIBRATE_DURATION = 200L;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        initBeepSound();

    }

    public void initViews()
    {
        mBtnScan = (Button)this.findViewById(R.id.btn_scan);
        mBtnSynchronous = (Button)this.findViewById(R.id.btn_synchronous);
        mResult = (TextView)this.findViewById(R.id.result);
        mQrcodeBitmap = (ImageView)this.findViewById(R.id.qrcode_bitmap);
        mBtnScan.setOnClickListener(this);
        mBtnSynchronous.setOnClickListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SCANNIN_GREQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();

                    String result = bundle.getString("result");

                    String strs[] = result.split(",");
                    String name = strs[0].split("=")[1];
                    String phone = strs[1].split("=")[1];
                    List<ScanModel> models = DBOperator.getInstance().query(ScanModel.class, "name='" + name + "' and phone = '"+phone+"'");
//                    mResult.setText(bundle.getString("result"));
//
//                    mQrcodeBitmap.setImageBitmap((Bitmap) data.getParcelableExtra("bitmap"));
                    Intent intent = new Intent(MainActivity.this,ResultActivity.class);
                    playBeepSoundAndVibrate();
                    if (models!=null&&models.size()!=0)
                    {

                        intent.putExtra("show","s");
                        startActivity(intent);
                    }
                    else
                    {
                        intent.putExtra("show","f");
                        startActivity(intent);
                    }
                }
                break;
        }
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_scan:
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, MipcaActivityCapture.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
                break;
            case R.id.btn_synchronous:
                ScanModel model = new ScanModel();
                model.setName("张三");
                model.setPhone("13811111111");
                DBOperator.getInstance().save(model);

                break;
        }
    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    com.zilla.android.lib.ui.R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }
    private void playBeepSoundAndVibrate() {
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };
}
